//
//  HomeHangqingCell.swift
//  ZYA
//
//  Created by 邱仙凯 on 2024/12/4.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit
import JJCollectionViewRoundFlowLayout_Swift

class HomeHangqingCell: BadgeCollectionViewCell {
    
    lazy var collectionView:UICollectionView = {
        // 1.创建layout
        
        let layout = JJCollectionViewRoundFlowLayout_Swift()
        layout.minimumLineSpacing = 1
        layout.minimumInteritemSpacing = 1
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        layout.scrollDirection = .horizontal
        // 2.创建UICollectionView
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.register(SmallHqCell.self, forCellWithReuseIdentifier: SmallHqCell.identifier)
        
     
        return collectionView
    }()
    
     var wsyArr = [QuotesModel]()
     var nsyArr = [QuotesModel]()
     var tzzArr = [QuotesModel]()
    var img: UIImageView = {
        let img = UIImageView()
        return img
    }()
    var view1: SmallHqView = {
        let v   = SmallHqView()
        v.title.text = "玉米(饲料原料)"
        v.layer.cornerRadius = 8
        return v
    }()
    var view2: SmallHqView = {
        let v   = SmallHqView()
        v.title.text = "豆粕(饲料原料)"
        v.layer.cornerRadius = 8
        return v
    }() 
    var view3: SmallHqView = {
        let v   = SmallHqView()
        v.title.text = "猪粮比"
        v.layer.cornerRadius = 8
        return v
    }()
    
    convenience required init(coder : NSCoder){
        self.init()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initUtil()
    }
    var coWidth:CGFloat!
    var coHeight:CGFloat!
    
    
    var pageControlWidth:CGFloat = 35
    var pageControlHeight:CGFloat = 5
    fileprivate lazy var pageControl: KSPageControl = {
        let pageControl = KSPageControl(frame: CGRect(x: 0, y: 0, width: pageControlWidth, height: pageControlHeight))
         return pageControl
    }()
    func initUtil() {
        coWidth = self.ks_width * 0.5
        coHeight = self.ks_height
        self.backgroundColor = .white
        self.contentView.backgroundColor = .white
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPagingEnabled = true
        
        
     
        pageControl.numberOfPage = 3
        
        self.contentView.addSubview(collectionView)
        contentView.addSubview(pageControl)
        self.contentView.addSubview(view1)
        self.contentView.addSubview(view2)
        self.contentView.addSubview(view3)
        collectionView.snp.makeConstraints { (make) in
            make.left.equalTo(self.contentView).offset(10)
            make.top.equalTo(self.contentView)
            make.height.equalTo(coHeight)
            make.width.equalTo(coWidth)
          }
        pageControl.snp.makeConstraints { make in
            make.bottom.equalTo(collectionView).offset(-7)
            make.centerX.equalTo(collectionView)
            make.width.equalTo(pageControlWidth)
            make.height.equalTo(pageControlHeight)
        }
       
        view1.snp.makeConstraints { (make) in
             make.top.equalTo(self.contentView)
            make.height.equalTo(self).multipliedBy(0.3)
            make.width.equalTo(self).multipliedBy(0.42)
            make.right.equalToSuperview().offset(-10)
        }
        view2.snp.makeConstraints { (make) in
             make.centerY.equalTo(self.contentView)
            make.height.equalTo(self).multipliedBy(0.3)
            make.width.equalTo(view1)
            make.right.equalToSuperview().offset(-10)
        }
        view3.snp.makeConstraints { (make) in
             make.bottom.equalTo(self.contentView)
            make.height.equalTo(self).multipliedBy(0.3)
            make.width.equalTo(view1)
            make.right.equalToSuperview().offset(-10)
        }
     
    }
    func showQuotesData(_ models:[QuotesModel]) {
        for model in models {
            if model.zTypeId.unwrap == "4" {
                
                if checkPlatform(type: .aoWang) && model.zChangePrice.unwrap == "报价平稳" {
                    view1.boLeft.textColor = UIColor(kshex: "#333333")
                    view1.img.extHidden(hidden: true)
                    
                } else {
                    view1.img.extHidden(hidden: false)
                    
                    if model.zChangePrice.unwrap.contains("-") {
                        view1.setStatus(up: false)
                    } else {
                        view1.setStatus(up: true)
                    }
                }
                
                view1.boLeft.text = model.zPrice.unwrap
                view1.boRight.text = model.zChangePrice.unwrap
            } else if model.zTypeId.unwrap == "5" {
                if checkPlatform(type: .aoWang) && model.zChangePrice.unwrap == "报价平稳" {
                    view2.boLeft.textColor = UIColor(kshex: "#333333")
                    view2.img.extHidden(hidden: true)
                    
                } else {
                    view2.img.extHidden(hidden: false)
                    if model.zChangePrice.unwrap.contains("-") {
                        view2.setStatus(up: false)
                    } else {
                        view2.setStatus(up: true)
                    }
                }
                view2.boLeft.text = model.zPrice.unwrap
                view2.boRight.text = model.zChangePrice.unwrap
            } else if model.zTypeId.unwrap == "6" {
                view3.boLeft.text = model.zPigGrainRatio.unwrap
                view3.boRight.text = ""
            }
        }
 
    }
}
// MARK: -   代理和数据源
extension HomeHangqingCell:UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    
    
   
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
  
   
            return 3
     
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SmallHqCell.identifier, for: indexPath) as? SmallHqCell  else {
            fatalError()
        }
        var lastModel: QuotesModel?
        
         
        
        switch indexPath.row {
        case 0:
            lastModel = self.wsyArr.last
         
            cell.title.text = "生猪(外三元)"

            cell.hqlineV?.dataPoints = wsyArr.compactMap{doubleTran($0.zPrice)}
        case 1:
            lastModel = self.nsyArr.last

             cell.title.text = "生猪(内三元)"
            cell.hqlineV?.dataPoints = nsyArr.compactMap{doubleTran($0.zPrice)}

        case 2:
            lastModel = self.tzzArr.last

             cell.title.text = "生猪(土杂猪)"
            cell.hqlineV?.dataPoints = tzzArr.compactMap{doubleTran($0.zPrice)}

        default:
            break
        }
        if let laM = lastModel, laM.zChangePrice.unwrap.contains("-") {
            cell.bg.setGradient(type: .top2bottom, startColor: UIColor(kshex: "#DAFFDA"), endColor: UIColor(kshex: "#F8FFF8"))
            cell.lab2left.textColor = UIColor(kshex: "#33B07C")
            cell.upDownImg.extHidden(hidden: false)
            cell.upDownImg.image = UIImage(named: "down_ss")
            cell.lab3.textColor = UIColor(kshex: "#33B07C")
            cell.hqlineV?.lineColor = UIColor(kshex: "#33B07C")
            cell.hqlineV?.startColor = UIColor(kshex: "#33B07C")
            cell.hqlineV?.endColor = UIColor(kshex: "#DFFFDD")
 
            
        } else {
            
            if checkPlatform(type: .aoWang), let laM = lastModel, laM.zChangePrice.unwrap == "报价平稳" {
                cell.lab2left.textColor = .black //UIColor(kshex: "#333333")
                cell.upDownImg.extHidden(hidden: true)
                cell.lab3.textColor = UIColor(kshex: "#333333")
                cell.hqlineV?.lineColor = UIColor(kshex: "#333333")
                cell.hqlineV?.startColor = .clear
                cell.hqlineV?.endColor = .clear
                
                
                cell.bg.setGradient(type: .top2bottom, startColor: TempDetBg, endColor: TempDetBg)
                
            } else {
                
                cell.lab2left.textColor = UIColor(kshex: "#FF4A4A")
                cell.upDownImg.extHidden(hidden: false)
                cell.upDownImg.image = UIImage(named: "up_ss")
                cell.lab3.textColor = UIColor(kshex: "#FF4A4A")
                cell.hqlineV?.lineColor = UIColor(kshex: "#FF4A4A")
                cell.hqlineV?.startColor = UIColor(kshex: "#FF4A4A")
                cell.hqlineV?.endColor = UIColor(kshex: "#FFF6F4")
                
                
                cell.bg.setGradient(type: .top2bottom, startColor: UIColor(kshex: "#FFDBD5"), endColor: UIColor(kshex: "#FFF7F5"))
            }
        }
        
        if let pricess = lastModel?.zPrice {
            cell.lab2left.text = pricess
        } else {
            cell.lab2left.text = "[金额]"
        }
       
        
        
        
        if let laM = lastModel {
            if laM.zChangePrice.unwrap.contains("元/公斤") {
                cell.lab3.text = laM.zChangePrice.unwrap.replacingOccurrences(of: "元/公斤", with: "")
                cell.lab3right.text = "元/公斤"
            } else {
                cell.lab3.text = laM.zChangePrice.unwrap.replacingOccurrences(of: "元/吨", with: "")
                cell.lab3right.text = "元/吨"
            }
        } else {
         
        }
        
      
        cell.hqlineV?.setNeedsDisplay()
            return cell
    
    }
 
    
    
    // 设置itemsize
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
   
   
            return CGSize(width: coWidth, height: coHeight)
   
      
   
    }
    // 滑动停止调用方法
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let offSet = scrollView.contentOffset.x
        let tempIndex = offSet / coWidth
        self.pageControl.currentPage = Int(tempIndex)
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        scrollViewDidEndDecelerating(scrollView)
    }
    
    
}

extension HomeHangqingCell : JJCollectionViewDelegateRoundFlowLayout_Swift{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, borderEdgeInsertsForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: -5, left: newModuleLeading, bottom: 12, right: newModuleLeading)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, configModelForSectionAtIndex section: Int) -> JJCollectionViewRoundConfigModel_Swift {
        
      
            let model = JJCollectionViewRoundConfigModel_Swift.init()
            model.cornerRadius = 8
            model.backgroundColor = UIColor.white
            return model
   
 
    }
}
class SmallHqCell: UICollectionViewCell {
    
    var bg:GradientView = {
        let v = GradientView()
        v.layer.cornerRadius = 8
        v.layer.masksToBounds = true
        return v
    }()
    var upDownImg: UIImageView = {
        let img = UIImageView()
        return img
    }()
    var title: UILabel = {
        let lab :UILabel = UILabel()
        lab.font = UIFont.boldSystemFont(ofSize: 18)
        lab.numberOfLines = 2
        lab.text = "生猪(外三元)"
        return lab
    }()
    var lab2left: UILabel = {
        let lab :UILabel = UILabel()
        lab.font = UIFont.boldSystemFont(ofSize: 36)
        lab.textColor = UIColor(kshex: "#FF4A4A")

        lab.text = "金额"
        lab.numberOfLines = 2
        return lab
    }()

    var lab3 : UILabel = {
        let lab :UILabel = UILabel()
        lab.font = UIFont.boldSystemFont(ofSize: 18)
        lab.textColor = UIColor(kshex: "#FF4A4A")

        lab.numberOfLines = 2
        lab.text = "+[环比金额]"
        return lab
    }()
    var lab3right: UILabel = {
        let lab :UILabel = UILabel()
        lab.font = UIFont.boldSystemFont(ofSize: 13)
        lab.textColor = UIColor(kshex: "#8991B0")
        lab.text = "[单位]"
        lab.numberOfLines = 2
        return lab
    }()
    var hqlineV:GradientLineView?
    convenience required init(coder : NSCoder){
        self.init()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initUtil()
    }

    
    
    func initUtil() {
        bg.frame = self.bounds
        self.contentView.addSubview(bg)
        
  
        
        
        bg.addSubview(upDownImg)
       
        bg.addSubview(title)
        title.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(bg).offset(10)
        }
        bg.addSubview(lab2left)
        lab2left.snp.makeConstraints { (make) in
            make.left.equalTo(title)
            make.top.equalTo(title.snp.bottom).offset(8)
        }
        upDownImg.snp.makeConstraints { (make) in
            make.width.equalTo(22)
            make.height.equalTo(26)
            make.left.equalTo(lab2left.snp.right).offset(2)
            make.centerY.equalTo(lab2left)
        }
        bg.addSubview(lab3)
        bg.addSubview(lab3right)
        lab3.snp.makeConstraints { (make) in
            make.left.equalTo(title)
            make.top.equalTo(lab2left.snp.bottom).offset(8)
        }
        lab3right.snp.makeConstraints { (make) in
            make.left.equalTo(lab3.snp.right)
            make.centerY.equalTo(lab3)
        }
        
        hqlineV = GradientLineView(frame: CGRect(x: 10, y: bg.ks_height/2 + 30, width: bg.ks_width - 20, height: bg.ks_height/2 - 45))
        hqlineV?.backgroundColor = .clear

        bg.addSubview(hqlineV!)
        
        
    }
}


class SmallHqView:UIView {
    var img: UIImageView = {
        let img = UIImageView()
        return img
    }()
    var title: UILabel = {
        let lab :UILabel = UILabel()
         lab.font = UIFont.boldSystemFont(ofSize: 13)
        lab.textAlignment = .center
        lab.numberOfLines = 2
        return lab
    }()
 
    var boLeft: UILabel = {
        let lab :UILabel = UILabel()
        lab.font = UIFont.boldSystemFont(ofSize: 19)
        lab.textColor = UIColor(kshex: "#FF4A4A")
        lab.text = "--"
        lab.numberOfLines = 2
        return lab
    }()
    var boRight: UILabel = {
        let lab :UILabel = UILabel()
        lab.font = UIFont.systemFont(ofSize: 12)
        lab.textColor = UIColor(kshex: "#8991B0")
        lab.numberOfLines = 2
        lab.text = "[单位]"
        return lab
    }()
    func setStatus(up:Bool){
        if up {
            boLeft.textColor = UIColor(kshex: "#FF4A4A")
            img.image = UIImage(named: "up_ss")
        } else {
            boLeft.textColor = UIColor(kshex: "#33B07C")
            img.image = UIImage(named: "down_ss")

        }
        
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor(kshex: "#EDF5FF")
        addSubview(img)
        addSubview(title)
 
        title.snp.makeConstraints { (make) in
            make.left.equalTo(self).offset(15)
            make.top.equalTo(self).offset(10)
        }
   
        addSubview(boLeft)
        addSubview(img)
        addSubview(boRight)
        boLeft.snp.makeConstraints { (make) in
            make.left.equalTo(title)
            make.bottom.equalToSuperview().offset(-10)
        }
        img.snp.makeConstraints { (make) in
            make.left.equalTo(boLeft.snp.right).offset(2)
            make.centerY.equalTo(boLeft)
            make.width.equalTo(11)
            make.height.equalTo(16)
        }
        boRight.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.bottom.equalTo(boLeft)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
 

class HQChartView: UIView {

  
    var lineColor = UIColor(kshex: "#FF4A4A")  //#33B07C
    var dataPoints: [CGFloat] = [10, 20, 15, 30, 25, 35, 40]
    
    
    var startColor = UIColor(kshex: "#33B07C")
    var endColor = UIColor(kshex: "#DFFFDD")
    
//    UIColor(kshex: "#FF4A4A").cgColor, // 渐变起始颜色
//    UIColor(kshex: "#FFF6F4").cgColor
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        
    
        // 绘制折线图
        drawLineChart()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//    override func layoutSubviews() {
//        super.layoutSubviews()
//        self.shapeLayer?.frame = self.bounds
//    }

    func drawLineChart() {
        // 清除之前的图层（如果有）
        self.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
        
        
        
        
        
        guard dataPoints.count > 1 else { return } // 确保有足够点来绘制线段
        
        // 1. 创建折线的 UIBezierPath
        let linePath = UIBezierPath()
        let pointSpacing = self.frame.width / CGFloat(dataPoints.count - 1) // 点之间的间距
        let maxValue = CGFloat(dataPoints.max() ?? 0)
        let minValue = CGFloat(dataPoints.min() ?? 0)
        let valueRange = maxValue - minValue
        let scaleY = self.frame.height / valueRange
        for (index, value) in dataPoints.enumerated() {
            let x = CGFloat(index) * pointSpacing
            let y = self.frame.height - (value - minValue) * scaleY

//            let y = rect.height - value // y 值从下往上绘制
            let point = CGPoint(x: x, y: y)
            
            if index == 0 {
                linePath.move(to: point) // 起始点
            } else {
                linePath.addLine(to: point) // 连接到下一个点
            }
        }
        
        // 2. 绘制折线
        lineColor.setStroke() // 设置线条颜色
        linePath.lineWidth = 2
        linePath.stroke()
        
        // 3. 创建渐变图层
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors = [
            
            startColor.cgColor, // 渐变起始颜色
            endColor.cgColor
            // 渐变结束颜色
        ]
        gradientLayer.startPoint = CGPoint(x: 0.5, y: 0) // 渐变从顶部开始
        gradientLayer.endPoint = CGPoint(x: 0.5, y: 1) // 渐变到底部结束
        gradientLayer.frame = self.bounds // 覆盖整个视图
        
        // 4. 创建裁剪路径（折线下方区域）
        let gradientPath = UIBezierPath()
        gradientPath.append(linePath) // 添加折线路径
        
        // 添加底部区域路径
         let lastPoint = linePath.currentPoint
            gradientPath.addLine(to: CGPoint(x: lastPoint.x, y: self.frame.height)) // 从最后一个点到底部
            gradientPath.addLine(to: CGPoint(x: 0, y: self.frame.height)) // 从底部右侧到左下角
            gradientPath.close() // 闭合路径
 
        
        // 5. 使用 CAShapeLayer 应用裁剪路径
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = gradientPath.cgPath
        gradientLayer.mask = shapeLayer
        
        // 6. 将渐变图层添加到视图
        self.layer.addSublayer(gradientLayer)
        
        
    }
}


// 使用示例
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let gradientLineView = GradientLineView(frame: CGRect(x: 0, y: 100, width: self.view.frame.width - 30, height: 200))
        gradientLineView.backgroundColor = .white
        
        let vvvvv = HQChartView(frame: CGRect(x: 0, y: 300, width: self.view.frame.width - 30, height: 200))
        vvvvv.backgroundColor = .white
        
        
        view.addSubview(gradientLineView)
        view.addSubview(vvvvv)

    }
}
